package com.onlinelibrary.activities.main.ui.service;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.util.Log;
import android.widget.SearchView;

import androidx.databinding.BindingAdapter;
import androidx.fragment.app.FragmentActivity;
import androidx.lifecycle.ViewModel;

import com.onlinelibrary.activities.App;
import com.onlinelibrary.activities.web.WebActivity;
import com.onlinelibrary.adapter.ServiceAdapter;
import com.onlinelibrary.bean.ServiceBean;
import com.onlinelibrary.databinding.FragmentServiceBinding;
import com.onlinelibrary.utils.Http;

import org.jetbrains.annotations.NotNull;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class ServiceVM extends ViewModel {
    @SuppressLint("StaticFieldLeak")
    private static FragmentServiceBinding binding;
    @SuppressLint("StaticFieldLeak")
    private static FragmentActivity requireActivity;
    public static final List<ServiceBean> data=new ArrayList<>();
    public static final List<ServiceBean> searchData=new ArrayList<>();
    public ServiceVM() {}
    public void setBinding(FragmentServiceBinding binding, ServiceFragment serviceFragment, FragmentActivity requireActivity) {
        ServiceVM.binding=binding;
        ServiceVM.requireActivity=requireActivity;
        binding.setAdp(new ServiceAdapter(requireActivity,data));
        binding.serviceList.setOnItemClickListener((parent, view, position, id) -> {
            ServiceBean bean = data.get(position);
            try {
                JSONObject jo=new JSONObject();
                jo.put("type","new_visit");
                jo.put("position", bean.name);
                Http.post(jo, "visit/", new Callback() {
                    @Override public void onFailure(@NotNull Call call, @NotNull IOException e){}
                    @Override public void onResponse(@NotNull Call call, @NotNull Response response){}
                });
            } catch (Exception e) {
                e.printStackTrace();
            }
            Http.get("article/?type=get_url&title=" + bean.name, new Callback() {
                @Override
                public void onFailure(@NotNull Call call, @NotNull IOException e) { }
                @Override
                public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                    try {
                        assert response.body() != null;
                        App.url= new JSONObject(response.body().string()).getString("data");
                        serviceFragment.startActivity(new Intent(requireActivity, WebActivity.class));
                        refresh();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            });
        });
        refresh();
    }
    private void refresh() {
        data.clear();
        searchData.clear();
        Http.get("article/?type=get_title&start=0&end=1000", new Callback() {
            @Override public void onFailure(@NotNull Call call, @NotNull IOException e) { }
            @Override public void onResponse(@NotNull Call call, @NotNull Response response) {
                try {
                    assert response.body() != null;
                    JSONArray ja = new JSONObject(response.body().string()).getJSONArray("data");
                    for (int i = 0; i < ja.length(); i++) {
                        Http.get("visit/?type=get_visit&position=" + ja.getString(i), new Callback() {
                            @Override
                            public void onFailure(@NotNull Call call, @NotNull IOException e) { }
                            @Override
                            public void onResponse(@NotNull Call call, @NotNull Response response) {
                                requireActivity.runOnUiThread(() -> {
                                    try {
                                        String count = response.body().string();
                                        data.add(new ServiceBean(response.request().url().queryParameter("position"),count));
                                        searchData.add(new ServiceBean(response.request().url().queryParameter("position"),count));
                                        binding.getAdp().notifyDataSetChanged();
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                });
                            }
                        });
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
    @BindingAdapter("bindSearchView")
    public static void bindSearchView(SearchView searchView,ServiceVM serviceVM){
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                return false;
            }
            @Override
            public boolean onQueryTextChange(String newText) {
                data.clear();
                for (ServiceBean serviceBean:searchData) {
                    if (serviceBean.name.contains(newText)){
                        data.add(serviceBean);
                    }
                }
                requireActivity.runOnUiThread(() -> binding.getAdp().notifyDataSetChanged());
                return false;
            }
        });
    }
}